﻿//-----------------------------------------------------------------------
// <summary>
//  The file contains a class that used to treat style cop settings 
// </summary>
// <copyright file="AutoPopulateExportedViewsBehavior.cs" company="DSSoftLogic">
//     Copyright@ DSSoftLogic 2011, Non-Commercial. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Property.Silverlight.Infrastructure
{
    using System;
    using System.ComponentModel.Composition;
    using Microsoft.Practices.Prism.Regions;

    /// <summary>
    /// The AutoPopulateExportedViewsBehavior infrastructure discovers the views in the container and automatically populates them into the associated region, 
    /// </summary>
    [Export(typeof(AutoPopulateExportedViewsBehavior))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class AutoPopulateExportedViewsBehavior : RegionBehavior, IPartImportsSatisfiedNotification
    {
        /// <summary>
        /// Gets or sets of RegisteredViews property will use 
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "MEF injected values"), ImportMany(AllowRecomposition = true)]
        public Lazy<object, IViewRegionRegistration>[] RegisteredViews { get; set; }

        /// <summary>
        /// OnImportsSatisfied method.
        /// </summary>
        public void OnImportsSatisfied()
        {
            this.AddRegisteredViews();
        }

        /// <summary>
        /// OnAttach method.
        /// </summary>
        protected override void OnAttach()
        {
            this.AddRegisteredViews();
        }

        /// <summary>
        /// AddRegisteredViews methods.
        /// </summary>
        private void AddRegisteredViews()
        {
            if (this.Region != null)
            {
                foreach (var viewEntry in this.RegisteredViews)
                {
                    if (viewEntry.Metadata.RegionName == this.Region.Name)
                    {
                        var view = viewEntry.Value;

                        if (!this.Region.Views.Contains(view))
                        {
                            this.Region.Add(view);
                        }
                    }
                }
            }
        }
    }
}
